<template>
  <div class="component-upload-image">
    <div class="upload-container">
      <el-upload
          multiple
          :action="uploadFileUrl"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :before-upload="handleBeforeUpload"
          :limit="limit"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          name="file"
          :on-remove="handleRemove"
          :show-file-list="true"
          :headers="headers"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :class="{hide: this.fileList.length >= this.limit}"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </div>

    <!-- 恢复上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>

    <el-dialog
        :visible.sync="dialogVisible"
        title="预览"
        width="800"
        append-to-body
    >
      <img
          :src="dialogImageUrl"
          style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getAccessToken } from "@/utils/auth";

export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_API, // 添加 baseUrl
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址
      headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
      fileList: []
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          let list = [];
          if (Array.isArray(val)) {
            list = val;
          } else if (typeof val === 'string') {
            // 尝试解析JSON字符串
            try {
              const parsed = JSON.parse(val);
              if (Array.isArray(parsed)) {
                list = parsed;
              } else {
                list = val.split(',').filter(item => item.trim());
              }
            } catch (e) {
              list = val.split(',').filter(item => item.trim());
            }
          } else {
            list = [val];
          }
          
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              return { name: item, url: item };
            } else if (item && typeof item === 'object') {
              // 如果是对象格式，使用 sattDir 作为 url
              return { 
                name: item.name || item.sattDir || 'image', 
                url: item.sattDir || item.url || item.name 
              };
            }
            return item;
          });
        } else {
          this.fileList = [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 删除图片
    handleRemove(file, fileList) {
      const findex = this.fileList.findIndex(f => f.name === file.name || f.url === file.url);
      if(findex > -1) {
        this.fileList.splice(findex, 1);
        
        // 如果父组件有处理方法，直接调用
        if (this.$parent && this.$parent.handleImageUpload) {
          this.$parent.handleImageUpload(this.fileList);
        } else {
          this.$emit("input", this.listToString(this.fileList));
        }
      }
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      if (res.code === 0 && res.data) {
        this.uploadList.push({ name: res.data, url: res.data });
        if (this.uploadList.length === this.number) {
          this.fileList = this.fileList.concat(this.uploadList);
          this.uploadList = [];
          this.number = 0;
          
          // 如果父组件有处理方法，直接调用
          if (this.$parent && this.$parent.handleImageUpload) {
            this.$parent.handleImageUpload(this.fileList);
          } else {
            this.$emit("input", this.listToString(this.fileList));
          }
          
          this.$modal.closeLoading();
        }
      } else {
        this.$modal.msgError(res.msg || "上传失败");
        this.$modal.closeLoading();
        this.number--;
      }
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          return !!(fileExtension && fileExtension.indexOf(type) > -1);
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      // 始终返回图片url数组
      return list.map(item => item.url);
    }
  }
};
</script>
<style scoped lang="scss">
.component-upload-image {
  width: 100%;
}

// 恢复原80x80样式
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  line-height: 80px;
}

:deep(.el-upload-list--picture-card) {
  display: inline-flex;
  flex-wrap: nowrap;
  margin: 0;
  padding: 0;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  margin-bottom: 0;
  flex-shrink: 0;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-container {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 10px;
  scrollbar-width: thin;
  scrollbar-color: #909399 #f4f4f5;

  &::-webkit-scrollbar {
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f4f4f5;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #909399;
    border-radius: 3px;
  }
}

// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
  display: none;
}

// 去除动画效果
:deep(.el-list-enter-active),
:deep(.el-list-leave-active),
:deep(.el-list-enter),
:deep(.el-list-leave-active) {
  transition: none !important;
  opacity: 1 !important;
  transform: none !important;
}
</style>

